// pages/classify/index/index.js
import userIndex from '../../../api/user';
import Index  from '../../../api/index';
import shopCar from '../../../api/shopCar';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabbar: {},
    carNum:0,
    modelPhone:false,
    isPhone:app.globalData.isPhone,
    isIphoneX:app.globalData.isIphoneX,
    userInfor:null,
    nickname:'',
    headImgUrl:'',
    question: 0,
    waitPay: 0,
    waitReceipt: 0,
    waitSend: 0,
    codeImg:'',
    isCodeMode:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 页面加载
    var that = this
    if(app.globalData.isIphoneX){
      this.setData({
        isIphoneX:app.globalData.isIphoneX
      })
    }else{
      setTimeout(()=>{
        that.setData({
          isIphoneX:app.globalData.isIphoneX
        })
      },100)
    }
    app.editTabBar()
    if(app.globalData.isPhone){
      this.getUserInfo()
    }
    that.setData({
      isPhone:app.globalData.isPhone
    })
    this.getOrderNum()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  getOrderNum(){
    userIndex.apiorderNum().then(res=>{
      this.setData({
        question:res.data.question||0,
        waitPay:res.data.waitPay||0,
        waitReceipt:res.data.waitReceipt||0,
        waitSend:res.data.waitSend||0,
      })
    })
  },
  getPhone(){
    wx.makePhoneCall({
      phoneNumber:'4006066086'
      })
  },
  //获取用户信息
  getUserInfo(){
    userIndex.apiGetUserInfo().then(res=>{
      this.setData({
        userInfor:res.data,
        nickname:res.data.nickname,
        headImgUrl:res.data.headImgUrl,
        isPhone:res.data.phone?true:false
      })
    })
  },
  //退出登录
  logOut(){
    var that=this
    wx.showModal({
      title: '提示',
      content: '确认退出当前账号，退出后部分功能无法使用',
      success (res) {
        if (res.confirm) {
          that.setData({
            userInfor:'',
            isPhone:false
          })
          app.globalData.isPhone=false
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
   
  },
  onChooseAvatar(e) {
    var that=this
    const { avatarUrl } = e.detail 

    wx.uploadFile({
      url: app.globalData.host +'/upload-file',
      name: 'file',
      filePath: avatarUrl,
      success: res => {
        var row=JSON.parse(res.data)
        if(row.code==200){
          that.setData({
            headImgUrl:row.data.fileUrl,
          })
          that.getUserProfile()
        }
      },
      fail: function (res) {
        console.log(res)
        wx.showToast({
          title: '上传失败',
          icon: 'none',
          duration:3000
        });
      },
    });
  },
  iconEdit(){
    wx.showToast({
      title: '直接点击头像或昵称进行修改',
      icon: 'none',
      duration:3000
    });
  },
   //获取昵称
   setnickname(e){
    this.setData({
      nickname:e.detail.value,
    })
    this.getUserProfile()
  },
  getUserProfile(){
    var that=this
    var param={
      headImgUrl:that.data.headImgUrl||'',
      nickname:that.data.nickname||'',
      email:this.data.userInfor.email,
      phone:this.data.userInfor.phone,
      sex:this.data.userInfor.sex,
    }
    userIndex.apiUpdateUserInfo(param).then(res=>{
      that.getUserInfo()
    })
  },
  login(){
    var that=this
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log(res)
          var params={
            code:res.code,
            referrerId:''
          }
          Index.apiWxappLogin(params).then(res=>{
            wx.setStorageSync('userInfo',res.data)
            wx.setStorageSync('token',res.data.token)
            if(res.data.data.phone){
              app.globalData.isPhone=true
              that.getUserInfo()
            }else{
              this.globalData.isPhone=false
            }
            
          })
        }
      },
    });
  },

  getPhoneNumber(e){
    var that=this
    var phoneCode=e.detail.code
    if(phoneCode){
      userIndex.apigetPhone({code:phoneCode}).then(res=>{
        app.globalData.isPhone=res.data.phone?true:false
        this.setData({
          userInfor:res.data,
          nickname:res.data.nickname,
          headImgUrl:res.data.headImgUrl,
          isPhone:res.data.phone?true:false,
          modelPhone:false,
        })
        that.getUserInfo()
      })
    }
  },
  getLoginBtn(){
    this.setData({
      modelPhone:true,
    })
  },
  closeLoginBtn(){
    this.setData({
      modelPhone:false,
    })
  },
  //推广
  promotionCenter(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.requestSubscribeMessage({
      tmplIds: ['h2_zHz8edyi4Yrmy0_SEEHQTbnmeRoqnsWAT0rN_OBY'],
      complete (complete) {
        wx.navigateTo({
          url: `/pages/user/promotionCenter/promotionCenter`,
        })
      }
    })
    
  },
  //优惠券
  coupon(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: `/pages/user/coupon/coupon`,
    })
  },
  //订单
  getOrder(e){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    var status=e.currentTarget.dataset.status
    wx.navigateTo({
      url: `/pages/user/order/order?status=${status}`,
    })
  },
  // 开票管理
  invoiceManage(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: `/pages/user/invoiceManage/invoiceManage`,
    })
  },
  //售后订单
  afterSalesOrder(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: `/pages/user/afterSalesOrder/afterSalesOrder`,
    })
  },
  //地址
  getAdderss(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: `/pages/user/address/address`,
    })
  },
  //足迹
  footprint(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: '/pages/user/footprint/footprint',
    })
  },
  //收藏
  Collection(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: '/pages/user/Collection/Collection',
    })
  },
  //
  getabout(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: '/pages/user/about/about',
    })
  },
  getaboutquestions(){
    if(!this.data.isPhone){
      this.getLoginBtn()
      return false
    }
    wx.navigateTo({
      url: '/pages/user/questions/questions',
    })
  },
  getShopCarNum(){
    shopCar.apishopCarNum().then(res=>{
      this.setData({
        carNum:res.data?res.data.num:0,
      })
    })
  },
  getCode(){
    userIndex.apirecommonImg().then(res=>{
      this.setData({
        codeImg:res.data,
        isCodeMode:true,
      })
    })
  },
  closeCodeBtn(){
    this.setData({
      isCodeMode:false,
    })
  },
  saveAlbum(){
    var that=this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.writePhotosAlbum']) {
          // 用户已授权，可直接保存图片
          wx.downloadFile({
            url:that.data.codeImg,
            success: (res) => {
              const tempFilePath = res.tempFilePath;
              // 此处得到临时文件路径，可用于保存到相册
              wx.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success: () => {
                  wx.showToast({
                    title: '保存成功',
                    duration: 1000
                  });
                }
              });
            }
          });
        } else {
          // 发起首次授权请求
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                // 授权成功，保存图片
                wx.downloadFile({
                  url:that.data.codeImg,
                  success: (res) => {
                    const tempFilePath = res.tempFilePath;
                    // 此处得到临时文件路径，可用于保存到相册
                    wx.saveImageToPhotosAlbum({
                      filePath: tempFilePath,
                      success: () => {
                        wx.showToast({
                          title: '保存成功',
                          duration: 1000
                        });
                      }
                    });
                  }
                });
              },
              fail: () => {
                // 用户拒绝授权，可提示用户前往设置页面授权
                wx.showModal({
                  title: '提示',
                  content: '检测到您没有打开保存到相册的权限，是否前往设置打开？',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting();
                    }
                  }
                });
              }
            });
          // 用户未授权，需申请授权
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(app.globalData.isPhone){
      this.getShopCarNum()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var userId=wx.getStorageSync('userInfo')?wx.getStorageSync('userInfo').userId:''
    return {
      title: '火食集', // 分享标题
      path: `/pages/home/index/index?referrerId=${userId}`, // 分享路径，必须是已经存在的页面路径
      // imageUrl: 'https://example.com/share.jpg', // 分享图标
      success: function (res) {
        // 转发成功
        if (res.errMsg === 'shareAppMessage:ok') {
          console.log('分享成功');
        }
      },
      fail: function (res) {
        // 转发失败
        console.log('分享失败', res);
      }
    }
  }
})